# 省扶平台---厕所革命
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import pandas as pd
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 提供键盘按键的支持，比如：RETURN, F1, ALT等
from selenium.webdriver.common.keys import Keys
import user

from ModifyWorkingCapacity import (
    find_element_clear,
    find_element_click,
    find_element_input,
    iselement,
    load_cookies,
    switch_tab,
)

driver = webdriver.Edge()
driver.maximize_window()
driver.implicitly_wait(5)
load_cookies(driver)

driver.get("http://222.244.103.58:8980/js/a/login")
# 获取当前选项卡
new_tab = driver.current_window_handle
print("当前选项卡", new_tab)
driver.find_element(By.ID, "username").send_keys(user.User2.username)
driver.find_element(By.ID, "password").send_keys(user.User2.password)

# 登录
driver.find_element(By.ID, "btnSubmit").click()

# 依次点击相应链接
for i in user.param2:
    if find_element_click(driver, By.XPATH, i):
        continue
    else:
        break

# 新开一个选项卡
driver.execute_script(
    "window.open('http://222.244.103.58:8980/js/a/index#/js/a/tr/trHouseholdToiletInfo/collectList#采集户厕')"
)
# 获取所有选项卡
tab = driver.window_handles
print("所有选项卡", tab)

# 切换到新开的选项卡
driver.switch_to.window(tab[1])
print("切换到采集户厕选项卡", tab[1])

# frame[0]是系统首页
frame = driver.find_elements(By.TAG_NAME, "iframe")
id = frame[1].get_attribute("id")
switch_tab(driver, "id", id)
print("我是iframe", id)


# 等待省市县加载完毕
time.sleep(2)

# 后续操作 pandas openyxl，xlrd，，操作excel
# 读取excel数据源
df = pd.read_excel("2019年土坪厕改花名册最终版.xlsx")
for idx, row in df.iterrows():
    身份证号码 = row["身份证号码"]
    print(身份证号码)
    try:
        # Selenium问题-无法定位元素：{"method":"css selector"，"selector“-需要帮助解决此问题
        # 出现无法定位元素时使用原始写法可得到错误提示：driver.find_element(By.ID, "")
        # 参考网址https://cloud.tencent.com/developer/ask/sof/1221860
        find_element_input(driver, By.ID, "certificatesNo", 身份证号码)
    except Exception as e:
        print("等了10秒没有找到相应元素链接，无法输入，错误：", e)
        # print(idx)
    find_element_click(driver, By.CSS_SELECTOR, "button[type='submit']")
    find_element_click(driver, By.CSS_SELECTOR, "a[title='编辑']")

    # 又是form，真他妈恶心
    if iselement(driver, By.TAG_NAME, "iframe"):
        print("找到该元素")
        print("我是姓名弹出框", driver.find_element(By.ID, "fullName").text)
    time.sleep(1)

    # find_element_input(driver, By.ID, "fullName", "我是姓名")

    if idx == 0:
        break
r = driver.find_element(By.CSS_SELECTOR, 'iframe[id^="layui-layer-iframe"]')
driver.switch_to.frame(r)
print("我是姓名弹出框", driver.find_element(By.ID, "fullName").text)
find_element_clear(driver, By.ID, "certificatesNo")

time.sleep(2)
